package org.example;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.xml.ws.Response;
import java.io.IOException;

@WebServlet("/login")
public class LoginServlet extends HttpServlet {

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        System.out.println("进入 Login Servlet的doGet方法");
        req.getRequestDispatcher("/login.jsp").forward(req, resp);
}

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String username = req.getParameter("username");
        String password = req.getParameter("password");


       try{
           Subject subject= SecurityUtils.getSubject();
           UsernamePasswordToken token = new UsernamePasswordToken(username, password);
           subject.login(token);
           resp.sendRedirect("sucess.jsp");
       }
       catch (AuthenticationException e) {
           e.printStackTrace();
           req.setAttribute("ErrorInfo", "账号密码错误");
           req.getRequestDispatcher("/login.jsp").forward(req, resp);
       }
       catch (Exception e){
           e.printStackTrace();
       }
    }
}
